<?php
/**
 * memcache 存储session
 * @author yangzhiguo 2011/05/05
 * @开闭读写销毁回收等方法必须是public
 */
defined('IN_LK') or die('Access Denied');
class session_memcache
{
	private static $session_key = MEMCACHE_PREFIX;
	private static $memcache = null;
	private static $lifetime = SESSION_LIFE;
	
	public function __construct()
	{
		$this->connect();
		session_set_save_handler(array(&$this, 'open'), 
								 array(&$this, 'close'), 
								 array(&$this, 'read'), 
								 array(&$this, 'write'), 
								 array(&$this, 'destroy'), 
								 array(&$this, 'gc'));
		session_start();
	}
	
	/**
	 * 写入
	 */
	public function write($sid, $data)
	{
		$func = $data ? 'set' : 'replace';
		return self::$memcache->$func(self::session_key($sid), $data, MEMCACHE_COMPRESSED, self::$lifetime);
	}
	
	/**
	 * 读取
	 * @param string $sid session_id
	 */
	public function read($sid)
	{
		return self::$memcache->get(self::session_key($sid));
	}
	
	/**
	 * 销毁
	 */
	public function destroy($sid)
	{
		return self::$memcache->delete(self::session_key($sid));
	}
	
	/**
	 * 关闭
	 */
	public function close()
	{
		return true;
	}
	
	/**
	 * 垃圾回收
	 * memcache 本身会把过期数据删除掉
	 */
	public function gc($lifetime)
	{
		return true;
	}
	
	/**
	 * 打开session_id
	 */
	public function open($sid, $hander)
	{
		return true;
	}
	
	/**
	 * memcache初始化
	 */
	private function connect()
	{
		if(self::$memcache)
		{
			return true;
		}
		self::$memcache = new memcache;
		self::$memcache->connect(MEMCACHE_HOST, MEMCACHE_PORT) or die('Could not connect memcache');
	}
	
	/**
	 * mixed session_id
	 * @param  string $sid session_id
	 * @return string 加了前缀的session_id
	 */
	private static function session_key($sid)
	{
		return self::$session_key . $sid;
	}
}